from fastapi import APIRouter, Depends, HTTPException, status, Query
from typing import List, Dict, Any, Optional
import psutil
import os
from datetime import datetime

from app.dependencies_json import get_current_user, get_task_service
from app.models.schemas import APIResponse
from app.services.json_task_service import JSONTaskService
from app.storage.json_storage import storage

router = APIRouter(tags=["monitoring"])

@router.get("/health", response_model=APIResponse[Dict[str, Any]])
def health_check():
    """健康检查"""
    try:
        # 检查数据目录
        data_dir_exists = os.path.exists("data")
        
        # 检查数据文件
        data_files = {
            "users.json": os.path.exists("data/users.json"),
            "tasks.json": os.path.exists("data/tasks.json"),
            "sessions.json": os.path.exists("data/sessions.json"),
            "logs.json": os.path.exists("data/logs.json")
        }
        
        health_data = {
            "status": "healthy",
            "timestamp": datetime.utcnow().isoformat(),
            "data_directory": data_dir_exists,
            "data_files": data_files,
            "storage_type": "JSON Files"
        }
        
        return APIResponse(
            message="系统健康",
            data=health_data
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"健康检查失败: {str(e)}"
        )

@router.get("/system", response_model=APIResponse[Dict[str, Any]])
def get_system_info(
    current_user: dict = Depends(get_current_user)
):
    """获取系统信息"""
    try:
        # 获取系统资源信息
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        
        # 获取数据统计
        users_count = len(storage.get_users())
        tasks_count = len(storage.get_tasks())
        
        system_info = {
            "cpu_usage": cpu_percent,
            "memory": {
                "total": memory.total,
                "available": memory.available,
                "percent": memory.percent,
                "used": memory.used
            },
            "disk": {
                "total": disk.total,
                "used": disk.used,
                "free": disk.free,
                "percent": (disk.used / disk.total) * 100
            },
            "data_statistics": {
                "users_count": users_count,
                "tasks_count": tasks_count
            },
            "timestamp": datetime.utcnow().isoformat()
        }
        
        return APIResponse(
            message="获取系统信息成功",
            data=system_info
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取系统信息失败: {str(e)}"
        )

@router.get("/tasks/stats", response_model=APIResponse[Dict[str, Any]])
def get_task_statistics(
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """获取任务统计信息"""
    try:
        tasks = storage.get_tasks()
        
        # 统计各状态的任务数量
        status_counts = {}
        total_tasks = len(tasks)
        
        for task in tasks:
            status = task.get('status', 'unknown')
            status_counts[status] = status_counts.get(status, 0) + 1
        
        # 计算成功率
        completed_tasks = status_counts.get('completed', 0)
        failed_tasks = status_counts.get('failed', 0)
        total_finished = completed_tasks + failed_tasks
        success_rate = (completed_tasks / total_finished * 100) if total_finished > 0 else 0
        
        stats = {
            "total_tasks": total_tasks,
            "status_distribution": status_counts,
            "success_rate": round(success_rate, 2),
            "completed_tasks": completed_tasks,
            "failed_tasks": failed_tasks,
            "running_tasks": status_counts.get('running', 0),
            "pending_tasks": status_counts.get('pending', 0),
            "timestamp": datetime.utcnow().isoformat()
        }
        
        return APIResponse(
            message="获取任务统计成功",
            data=stats
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取任务统计失败: {str(e)}"
        )

@router.get("/logs", response_model=APIResponse[List[Dict[str, Any]]])
def get_system_logs(
    limit: int = Query(100, ge=1, le=1000, description="日志数量限制"),
    task_id: Optional[str] = Query(None, description="任务ID过滤"),
    current_user: dict = Depends(get_current_user)
):
    """获取系统日志"""
    try:
        logs = storage.get_logs(task_id=task_id, limit=limit)
        
        return APIResponse(
            message="获取系统日志成功",
            data=logs
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取系统日志失败: {str(e)}"
        )

@router.get("/storage", response_model=APIResponse[Dict[str, Any]])
def get_storage_info(
    current_user: dict = Depends(get_current_user)
):
    """获取存储信息"""
    try:
        data_dir = "data"
        storage_info = {
            "storage_type": "JSON Files",
            "data_directory": data_dir,
            "files": {}
        }
        
        # 检查各个数据文件的大小
        file_names = ["users.json", "tasks.json", "sessions.json", "logs.json"]
        total_size = 0
        
        for file_name in file_names:
            file_path = os.path.join(data_dir, file_name)
            if os.path.exists(file_path):
                file_size = os.path.getsize(file_path)
                storage_info["files"][file_name] = {
                    "exists": True,
                    "size_bytes": file_size,
                    "size_kb": round(file_size / 1024, 2),
                    "modified": datetime.fromtimestamp(os.path.getmtime(file_path)).isoformat()
                }
                total_size += file_size
            else:
                storage_info["files"][file_name] = {
                    "exists": False,
                    "size_bytes": 0,
                    "size_kb": 0,
                    "modified": None
                }
        
        storage_info["total_size_bytes"] = total_size
        storage_info["total_size_kb"] = round(total_size / 1024, 2)
        storage_info["total_size_mb"] = round(total_size / (1024 * 1024), 2)
        
        return APIResponse(
            message="获取存储信息成功",
            data=storage_info
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取存储信息失败: {str(e)}"
        )
